<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="540px"
    @close="handleClose">
    <el-transfer
      v-model="roles"
      :titles="['角色列表', '已选择角色']"
      :props="{
        key: 'id',
        label: 'name'
      }"
      :data="dataList"/>
    <div slot="footer" class="dialog-footer">
      <el-button @click="resetForm">取 消</el-button>
      <el-button :loading="isSubmit" type="primary" @click="handleSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import resultCode from '@/utils/resultCode'
import { getList } from '@/api/role'
import { getRoleByAccountId, saveRoleByAccountId } from '@/api/account'

export default {
  data() {
    return {
      visible: false,
      isSubmit: false,
      title: '分配角色',
      roles: [],
      accountId: null,
      formSearch: {
        name: '',
        code: '',
        status: '',
        beginDate: '',
        endDate: ''
      },
      dataList: []
    }
  },
  methods: {
    init(id) {
      this.accountId = id
      this.visible = true
      this.searchList()
      this.getRole()
    },
    searchList: function() {
      getList(this.formSearch).then(response => {
        const result = response.data// 请求接口返回的内容
        if (result.code === resultCode.SUCCESS) {
          console.log('=========datalist=========')
          console.log(result.data)
          this.dataList = result.data
        }
      })
    },
    getRole: function() {
      this.roles = []
      getRoleByAccountId(this.accountId).then(response => {
        const result = response.data// 请求接口返回的内容
        if (result.code === resultCode.SUCCESS) {
          const roleArray = result.data
          console.log('=========roleArray=========')
          console.log(roleArray)
          if (roleArray) {
            roleArray.forEach(role => {
              this.roles.push(role.id)
            })
          }
        }
      })
    },
    handleSubmit: function() {
      this.isSubmit = true
      const strRoleIds = this.roles.join(',')
      saveRoleByAccountId(this.accountId, strRoleIds).then(response => {
        const result = response.data // 请求接口返回的内容
        if (result.code === resultCode.SUCCESS) {
          this.visible = false
          this.$message.success('分配成功')
        }
        this.isSubmit = false
      }).catch(err => {
        this.isSubmit = false
      })
    },
    resetForm: function() {
      this.visible = false
    },
    handleClose: function() {
      this.isSubmit = false
    }
  }
}
</script>
